<?php


define("FORREADING", 1);
define("FORWRITING", 2);
define("FORAPPENDING", 8);

define ("YYYYDMMDDD", "YYYY-MM-DD");
define ("YYYYDMMDDDSHHCHHCSS", "DD-MM-YYYY HH:MM:SS");

define ("PRODUCTNAME", "Politie Narrowcast");

define ("THECONNECTION", 'mysql:host=localhost;dbname=narrowbase');
define ("THEREADCONNECTION", "DSN=kabelread;");
define ("THEARCHIVECONNECTION", 'mysql:host=localhost;dbname=narrowarchive');
define ("THEONLINECONNECTION", 'mysql:host=localhost;dbname=narrowonline');
define ("LOG", '/var/log/apache2/')
#' the first running server is considered the master server
# TODO:
# if application("narrowcast.server") = "" then application("narrowcast.server") = request.serverVariables("REMOTE_HOST")

$username = "narrow";
$password = "narrow";
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    PDO::ATTR_PERSISTENT => true
); 

$tmpConnection = null;
$readConnection = null;
$archiveConnection = null;
$onlineConnection = null;

function closeDatabase()
{
	$tmpConnection = null;
}

function openArchive() 
{
	$archiveConnection = new PDO($THEARCHIVECONNECTION, $username, $password, $options);
}

function closeArchive() 
{
	$archiveConnection = null;
}

function openOnline()
{
	$onlineConnection = new PDO($THEONLINECONNECTION, $username, $password, $options);
}

function closeOnline()
{
	$onlineConnection = null;
}	

function makeParam($txt)
{
	$result = null;

	foreach (explode('<br>', $txt) as $t) {
		$tmpArr = explode('=', $t, 2);
		$ub = count($tmpArr);
		if ($ub >= 1) 
		{
			$result = $result . '&' . urlencode($tmpArr[0]) . '=' . urlencode($tmpArr[1])
		}
	}
	return $result;
}

function register($pid, $pagename) 
{

	error_log(date('Y-m-d H:i:s') . ' [' . $pid . '][ ' . $_SERVER["HTTP_HOST"] . ']' . $pagename, 3, logname());

}

function registerCentral($pid, $pagename) {
	error_log(date('Y-m-d H:i:s') . ' [' . $pid . '][ ' . $_SESSION["loggedUser"] . ']' . $pagename, 3, 'log/kkserver.log');
}

function logname()
{
	return'log/host-' . $_SERVER["HTTP_HOST"] . '/' . date('YY-MM-DD') . '.log';
}


// sub setNP(pid, pagename, inhoud, pauze, bgImage, special, theInc)
// 	if request.serverVariables("REMOTE_HOST") = application("narrowcast.server") then
// 		application("kk_json") = "{'id': '" & pid & "', 'title': '" & replace(pagename, "'", "\'") & "', 'inhoud' : '"& replace(inhoud, "'", "\'") & "', 'pauze':'" & pauze & "', 'bgImage':'" & bgImage & "', 'special':'" & special & "'}"
// 	end if
// end sub

function monthname($monthNumber) {
	$months = array('januari', 'februari', 'maart', 'april', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december');
	return $months[$monthNumber];
}

function header() {
	echo <<<EOS
  <html>
		<head>
			<LINK REL="stylesheet" TYPE="text/css" HREF="style/editor.css">
			<script language="JavaScript" type="text/javascript" src="script/editor.js"></script>
			<title>$PRODUCTNAME Editor - PolitieMon</title>
		</head>

		<body bgcolor="white" background="sysimages/kabelkrantbg.gif">
EOS;
}

function footer() {
	echo <<<EOS
		<div align="right" class="username">$theUser</div>
		</body>
	</html>
EOS;
}

function formDateToDBString($what) {
	if ($what == "") {
		return $what;
	} else {
		$tmpArray = explode('/', $what);
		return sprintf('%04d%02d%02d', $tmpArray[2], $tmpArray[1], $tmpArray[0]);
	}
}

function DBStringToFormDate(what)
	if what = "" or isnull(what) then
		DBStringToFormDate = ""
	else
		DBStringToFormDate = cint(mid(what,7,2)) & "/" & cint(mid(what,5,2)) & "/" & cint(left(what, 4))
	end if
end function

function DBStringToShortDate(what)
	if what = "" or isnull(what) then
		DBStringToShortDate = ""
	else
		DBStringToShortDate = cint(mid(what,7,2)) & "/" & cint(mid(what,5,2))
	end if
end function

function formBoolToQuery(what)
	if what = "" then
		formBoolToQuery = "0"
	else
		formBoolToQuery = "1"
	end if
end function

function dagKort(datum)
	week = array("zo", "ma", "di", "wo", "do", "vr", "za")
	dagKort = week(weekday(datum) - 1)
end function

function niceDate(dateString, formatString)
	dim da, ta
	if trim(dateString) <> ""  then
		select case formatString
		case YYYYdMMdDD
			da = split(dateString, "-")
			y = cint(da(0))
			m = cint(da(1))
			d = cint(da(2))
		case DDdMMdYYYYsHHcMMcSS
			ta = split(dateString, " ")
			da = split(ta(0), "-")
			y = cint(da(2))
			m = cint(da(1))
			d = cint(da(0))
		end select
		niceDate = cstr(d) & " " & monthname(m) & " " & cstr(y)
	else
		niceDate = "?"
	end if
end function

function pageIsScheduled(rs)
	# rs is a record from vwcontent
	ok = true
	
	vandaagString = formDateToDBString(day(now()) & "/" & month(now()) & "/" & year(now()))

	if not isnull(rs("schemaid")) then
		if not rs( dagKort(now()) ) then ok = false
		if vandaagString < rs("van") and not rs("van") = "" then ok = false
		if vandaagString > rs("tot") and not rs("tot") = "" then ok = false
	end if
	
	pageIsScheduled = ok
end function

function extdate
	extdate = getExternalHTML("http://viewer1/rel2/datetime.asp")
end function

function extnow
	extnow = getExternalHTML("http://viewer1/rel2/datetime.asp?command=now")
end function

function getExternalHTML(url)
	  'Declare the variables, and set the value of the variable url as 
	  'the full URL of the requested page.
	  Dim xml, strData
	
	  'Next, create an instance of the MS XMLhttp component.
	  'old version, unstable server side performance so upgrade if you can
	  ' *** OLD *** Set xml = Server.CreateObject("Microsoft.XMLHTTP")
		
	  'new version, better server side performance
	  Set xml = Server.CreateObject("MSXML2.ServerXMLHTTP.3.0")
	
	  'Now open the connection, and send the request to the remote server. You 
	  'need to set the optional Async parameter to True on the open method for 
	  'this script to work. Otherwise, the waitForResponse method used 
	  'below will have no effect.
	  xml.Open "GET", url, true    ' the True specifies an asynchronous request
	  Call xml.Send()
	
	  'Turn off error handling
	  On Error Resume Next
	  
	  'Wait for up to 3 seconds if we've not gotten the data yet
	  If xml.readyState <> 4 then
	    xml.waitForResponse 60
	  End If
	
	  'Did an error occur?  If so, use a default value for our data
	  If Err.Number <> 0 then
	    strData = "error: " & err.description
	  Else
	    If (xml.readyState <> 4) Or (xml.Status <> 200) Then
	      'Abort the XMLHttp request
	      xml.Abort
	            
		  strData = "error xml.readyState=" & xml.readyState
	    Else
	      strData = xml.ResponseText
	    End If
	  End If
	getExternalHTML = strData
end function
?>